package CopyOnWriteArrayList_11;
import java.util.concurrent.CopyOnWriteArrayList;

public class 黑白名单过滤_读多写少场景 {
    private final CopyOnWriteArrayList<String> blacklist = new CopyOnWriteArrayList<String>();

    public 黑白名单过滤_读多写少场景() {
        // 初始化黑名单
        blacklist.add("恶意IP1");
        blacklist.add("恶意IP2");
    }

    public boolean isAllowed(String ip) {
        return !blacklist.contains(ip);
    }

    public void addToBlacklist(String ip) {
        blacklist.add(ip);
    }

    public static void main(String[] args) {
        final 黑白名单过滤_读多写少场景 filter = new 黑白名单过滤_读多写少场景();
        final int CHECK_THREADS = 20;
        final int UPDATE_THREADS = 3;

        // 创建IP检查线程
        for (int i = 0; i < CHECK_THREADS; i++) {
            final String ip = "192.168.1." + (i % 10); // 模拟10个不同IP
            new Thread(new Runnable() {
                public void run() {
                    try {
                        for (int j = 0; j < 5; j++) {
                            boolean allowed = filter.isAllowed(ip);
                            System.out.println(Thread.currentThread().getName() +
                                                       " 检查IP: " + ip + " 结果: " + (allowed ? "允许" : "拒绝"));
                            Thread.sleep((long)(Math.random() * 50)); // 模拟处理时间
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "检查线程-" + i).start();
        }

        // 创建黑名单更新线程
        for (int i = 0; i < UPDATE_THREADS; i++) {
            final String maliciousIp = "10.0.0." + i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep((long)(Math.random() * 200 + 100)); // 随机延迟
                        filter.addToBlacklist(maliciousIp);
                        System.out.println("已添加IP到黑名单: " + maliciousIp);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "更新线程-" + i).start();
        }

        // 等待所有操作完成
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}